package ice.webapp.filter;

import ice.webapp.action.ActionFactory;
import ice.webapp.action.BaseAction;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理所有Action请求
 */
public class RequestServlet extends HttpServlet {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 838195888384017584L;

    /**
     * {@inheritDoc}
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        handleActionRequest(request, response);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        handleActionRequest(request, response);
    }

    /**
     * 处理Action请求
     */
    private void handleActionRequest(HttpServletRequest request, HttpServletResponse response)
            throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String requestUri = request.getPathInfo();
        BaseAction action = ActionFactory.getFactory().getAction(requestUri);
        if (action != null) {
            action.setRequest(request);
            action.setResponse(response);
            action.invokeMethod(requestUri);
        }
    }
}
